// AI聊天功能JavaScript代码
(function() {
    'use strict';

    // 获取DOM元素
    const chatBody = document.getElementById('chatBody');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const temperatureSlider = document.getElementById('temperature');
    const temperatureValue = document.getElementById('temperatureValue');
    const maxTokensInput = document.getElementById('maxTokens');
    const streamModeCheckbox = document.getElementById('streamMode');

    // 聊天历史
    let chatHistory = [];

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 绑定事件
        sendButton.addEventListener('click', sendMessage);
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 绑定参数变化事件
        if (temperatureSlider) {
            temperatureSlider.addEventListener('input', function() {
                temperatureValue.textContent = this.value;
            });
        }

        // 绑定快捷问题
        const quickQuestions = document.querySelectorAll('.quick-question');
        quickQuestions.forEach(question => {
            question.addEventListener('click', function() {
                messageInput.value = this.textContent;
                sendMessage();
            });
        });
    });

    /**
     * 发送消息
     */
    function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        // 禁用发送按钮
        sendButton.disabled = true;

        // 添加用户消息到界面
        addMessage('user', message, false);

        // 添加到历史记录
        chatHistory.push({
            role: 'user',
            content: message
        });

        // 构建请求参数
        const chatRequest = {
            prompt: message,
            history: chatHistory.slice(0, -1), // 不包括当前消息
            temperature: temperatureSlider ? parseFloat(temperatureSlider.value) : 0.7,
            maxTokens: maxTokensInput ? parseInt(maxTokensInput.value) : 2048,
            streamMode: streamModeCheckbox ? streamModeCheckbox.checked : true // 默认启用流式模式
        };

        // 清空输入框
        messageInput.value = '';

        // 创建并显示AI的占位消息
        const aiMessageElement = addMessage('ai', '', true);

        // 使用fetch进行流式请求
        fetch('/api/ai/chat/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(chatRequest)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            console.log('开始接收流式数据...');
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = "";
            let buffer = "";

            function processStream() {
                return reader.read().then(({ done, value }) => {
                    if (done) {
                        console.log("Stream completed. 完整响应:", fullResponse);
                        updateMessage(aiMessageElement, fullResponse, false);
                        sendButton.disabled = false;
                        
                        // 添加到历史记录
                        if (fullResponse) {
                            chatHistory.push({
                                role: 'assistant',
                                content: fullResponse
                            });
                        }
                        return;
                    }

                    // 解码新的数据块
                    const chunk = decoder.decode(value, { stream: true });
                    buffer += chunk;
                    console.log('收到数据块:', chunk);
                    
                    // 按双换行符分割SSE事件
                    const events = buffer.split('\n\n');
                    buffer = events.pop() || ''; // 保留不完整的行

                    for (const event of events) {
                        if (!event.trim()) continue;
                        
                        console.log('处理SSE事件:', event);
                        
                        let eventType = '';
                        let eventData = '';
                        
                        // 解析事件类型和数据
                        const lines = event.split('\n');
                        for (const line of lines) {
                            if (line.startsWith('event: ')) {
                                eventType = line.slice(7).trim();
                            } else if (line.startsWith('data: ')) {
                                eventData = line.slice(6).trim();
                            }
                        }
                        
                        console.log('事件解析结果 - 类型:', eventType, '数据:', eventData);
                        
                        // 处理text事件
                        if (eventType === 'text' && eventData) {
                            try {
                                const parsedData = JSON.parse(eventData);
                                if (parsedData.text) {
                                    console.log('收到文本片段:', parsedData.text);
                                    fullResponse += parsedData.text;
                                    updateMessage(aiMessageElement, fullResponse, false);
                                }
                            } catch (e) {
                                console.warn('Failed to parse SSE text data:', eventData, e);
                            }
                        }
                        // 处理complete事件
                        else if (eventType === 'complete') {
                            console.log('收到完成事件');
                        }
                        // 处理error事件
                        else if (eventType === 'error') {
                            try {
                                const parsedData = JSON.parse(eventData);
                                console.log('收到错误事件:', parsedData.text);
                                updateMessage(aiMessageElement, `错误: ${parsedData.text}`, false);
                            } catch (e) {
                                console.warn('Failed to parse error data:', eventData, e);
                            }
                        }
                        // 处理没有事件类型的data行
                        else if (!eventType && eventData) {
                            console.log('收到没有事件类型的data行:', eventData);
                            try {
                                const parsedData = JSON.parse(eventData);
                                if (parsedData.text) {
                                    console.log('从无类型data行解析到文本:', parsedData.text);
                                    fullResponse += parsedData.text;
                                    updateMessage(aiMessageElement, fullResponse, false);
                                }
                            } catch (e) {
                                console.warn('Failed to parse data without event type:', eventData, e);
                            }
                        }
                    }

                    // 继续读取
                    return processStream();
                });
            }

            return processStream();
        })
        .catch(error => {
            console.error('Stream error:', error);
            updateMessage(aiMessageElement, `连接错误: ${error.message}`, false);
            sendButton.disabled = false;
        });
    }

    /**
     * 添加消息到聊天界面
     * @param {string} sender - 发送者 ('user' 或 'ai')
     * @param {string} text - 消息内容
     * @param {boolean} isLoading - 是否显示加载动画
     * @returns {HTMLElement} 创建的消息元素
     */
    function addMessage(sender, text, isLoading) {
        // 确保chatBody存在
        if (!chatBody) return null;

        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${sender}`;

        const avatar = document.createElement('div');
        avatar.className = 'avatar';
        avatar.textContent = sender === 'user' ? 'U' : 'AI';

        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';

        const textSpan = document.createElement('span');
        textSpan.className = 'text';
        textSpan.textContent = text;
        
        messageContent.appendChild(textSpan);

        if (isLoading) {
            const loadingSpan = document.createElement('span');
            loadingSpan.className = 'loading-dots';
            loadingSpan.innerHTML = '<span>.</span><span>.</span><span>.</span>';
            messageContent.appendChild(loadingSpan);
        }

        messageDiv.appendChild(avatar);
        messageDiv.appendChild(messageContent);
        chatBody.appendChild(messageDiv);

        // 滚动到底部
        chatBody.scrollTop = chatBody.scrollHeight;
        
        // 返回创建的消息元素
        return messageDiv;
    }

    /**
     * 更新消息内容
     * @param {HTMLElement} messageElement - 消息元素
     * @param {string} newText - 新的完整文本
     * @param {boolean} isLoading - 是否显示加载指示器
     */
    function updateMessage(messageElement, newText, isLoading) {
        if (!messageElement) return;

        const textSpan = messageElement.querySelector('.message-content .text');
        if (textSpan) {
            textSpan.textContent = newText;
        }

        let loadingSpan = messageElement.querySelector('.message-content .loading-dots');
        if (isLoading) {
            if (!loadingSpan) {
                loadingSpan = document.createElement('span');
                loadingSpan.className = 'loading-dots';
                loadingSpan.innerHTML = '<span>.</span><span>.</span><span>.</span>';
                messageElement.querySelector('.message-content').appendChild(loadingSpan);
            }
        } else {
            if (loadingSpan) {
                loadingSpan.remove();
            }
        }
    }

    /**
     * 清空聊天记录
     */
    function clearChat() {
        if (chatBody) {
            chatBody.innerHTML = '';
        }
        chatHistory = [];
    }

    // 将函数附加到window对象，使其在HTML中可调用
    window.sendMessage = sendMessage;
    window.clearChat = clearChat;
    window.addMessage = addMessage;
    window.updateMessage = updateMessage;

})();
